package com.xxx.DAO;

import com.xxx.entity.Book;
import com.xxx.util.JDBCUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class user_bookDao {
    private JDBCUtil util = new JDBCUtil();

    //检查该书有没有被当前用户借
    public int isBorrowed(String userId,String bName){
        String sql ="select DISTINCT bName from user_book ub  left join tb_user u on ub.uid=u.userId left join books b on ub.bid=b.id where u.userId=? and bName like ?";
        ResultSet rs=null;
        int result = 0;
        PreparedStatement ps = util.createPstmt(sql);
        try {
            ps.setString(1, userId);
            ps.setString(2, bName);
            rs=ps.executeQuery();
            if (rs.next()){result=1;}
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    //根据用户id查询改用户所借的书
    public List findBorrow(int uid){
        String sql="select DISTINCT b.* from user_book ub  left join tb_user u on ub.uid=u.userId left join books b on ub.bid=b.id where u.userId=?";
        ResultSet rs=null;
        PreparedStatement ps=util.createPstmt(sql);
        List list=new ArrayList();

        try {
            ps.setInt(1,uid);
            rs=ps.executeQuery();
            while (rs.next()){
                int id=rs.getInt("id");
                String bName2=rs.getString("bName");
                String bAut=rs.getString("bAut");
                String bPub=rs.getString("bPub");
                int bSum=rs.getInt("bSum");
                String path=rs.getString("path");
                Book book=new Book(id,bName2,bAut,bPub,bSum,path);
                list.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(rs);
        }
        return list;
    }

    //增加一本被借的书
    public int add(int userId,String id){
        String sql="insert into user_book (uid,bid) values(?,?)";
        int result = 0;
        PreparedStatement ps = util.createPstmt(sql);
        try {
            ps.setInt(1,userId);
            ps.setString(2,id);
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close();
        }
        return result;
    }
}
